package com.object;

import com.NettyServer;
import com.OtaService;
import com.sql.ConnectionErrorInfo;
import com.sql.SqlOperation;
import io.netty.channel.ChannelHandlerContext;

public class Gprs {
    private String gprsId;
    private ChannelHandlerContext ctx;
    private int port;
    private SqlOperation sqlOperation;


    public Gprs(String id, ChannelHandlerContext ctx){
        this.gprsId = id;
        this.ctx = ctx;
        this.port = Integer.parseInt(ctx.channel().localAddress().toString().split(":")[1]);
        this.sqlOperation = new SqlOperation(this);
    }

    public String getId(){
        return gprsId;
    }

    public String getRemoteAddr(){
        return ctx.channel().remoteAddress().toString();
    }

    public int getPort(){
        return this.port;
    }

    public ChannelHandlerContext getChannelHandlerContext(){return ctx;}

    private OtaService otaService;
    public void setOtaService(OtaService service){
        this.otaService = service;
    }
    public OtaService getOtaService(){
        return this.otaService;
    }

    public Gprs initialOtaService(){
        this.otaService = OtaService.create(this);
        return this;
    }

    public void fireOtaService(OtaObject ob)throws Exception{
        initialOtaService();
        this.otaService.setOtaObject(ob).startUpgrade();
        this.upgradeSendDone();
        //ctx.close();
        NettyServer.GPRS_OTASERVICE.put(this.gprsId, this.otaService);


    }

    public void errorConnectionProcess(byte[] msg) throws Exception{
        if (msg != null && msg.length > 0){
            int type = msg[0];
            byte[] addrBytes = new byte[msg.length - 1];
            System.arraycopy(msg,1,addrBytes,0,addrBytes.length);
            String addr = new String(addrBytes, "ASCII");
            ConnectionErrorInfo info = new ConnectionErrorInfo();
            info.setAddress(addr);
            info.setAddrType(type);
            rcvConnectionError(info);
        }
    }


    //region sql operation
    public void online(){
        this.sqlOperation.online();
    }

    public void offline(){
        this.sqlOperation.offline();
    }

    public void rcvConnectionError(ConnectionErrorInfo info){
        this.sqlOperation.insertConnectionErrorInfo(info);
    }

    public void otaFailed(String failedInfo){
        this.sqlOperation.updateOtaFailed(failedInfo);
    }

    public void otaSuccessed(String info){
       this.sqlOperation.updateOtaSuccessed(info);
    }
    private void upgradeSendDone(){
        this.sqlOperation.otaSendDone();
    }


    //endregion
}
